﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using TongHopBookFlightDAO;
using TongHopBookFlightDAO.DAO;
using System.Text.RegularExpressions;

namespace TongHopBookFlightCores.Cores
{
    public class RutTrichTrangJetstar
    {
        private string[] typeFlight = { "OneWay", "RoundTrip", "OpenJaw" };
        private HtmlDocument document;
        private string host = "http://booknow.jetstar.com/Search.aspx";
        private string data = "";
        int numFlights = 0;
        
        public void TimChuyenBayTheoMotChieu(string diemDi, string diemDen, DateTime ngaydi)
        {
            HtmlWeb web = new HtmlWeb();

            document= MakeUrl(diemDi, diemDen, ngaydi.Day, ngaydi.Month);

            if (document == null) throw new Exception("Nội dung HTML null");

            for (int i = 0; i < numFlights; i++)
            {
                ChuyenBay chuyenBay= new ChuyenBay();
                try
                
                {
                    HtmlNodeCollection moreraces = document.DocumentNode.SelectNodes("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr[1]/td[3]/div/div[1]/dl");
                    
                    HtmlNode DepartTime = document.DocumentNode.SelectSingleNode("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr["+( i + 1) +"]/td[1]/strong");
                    HtmlNode ArriveTime = document.DocumentNode.SelectSingleNode("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr[" + (i + 1) + "]/td[2]/strong");
                    //string Duration = document.DocumentNode.SelectSingleNode("//div[@class='fare-picker depart clearfix']//table[@class='domestic']/tbody/tr[" + (i + 1).ToString() + "]/td[3]/a").InnerText;
                    HtmlNode aircraftcode = document.DocumentNode.SelectSingleNode("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr[" + (i + 1) + "]/td[3]/div/div[1]/dl/dt/span");
                    HtmlNode giave = document.DocumentNode.SelectSingleNode("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr[" + (i + 1) + "]/td[4]/div[1]/label");
                    long Price = 0;
                    if (giave != null)
                    {
                        Price = long.Parse(Replacestring(giave.InnerText, @"\s|\n|VND|\.|,"));
                    }
                    string diemdung = "";
                    if (moreraces.Count <= 1)
                    {
                       HtmlNode Stop = document.DocumentNode.SelectSingleNode("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr[" + (i + 1) + "]/td[3]/span");
                       diemdung = Stop.InnerText;
                    }
                    else
                    {

                        for (int h = 0; h < moreraces.Count - 2; h = h + 2)
                        {
                            HtmlNode retuflight = document.DocumentNode.SelectSingleNode("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr[1]/td[3]/div/div[1]/dl[" + (h + 1) + "]/dd[2]");
                            diemdung = diemdung + GetPlaces(Replacestring(retuflight.InnerText, @"\n|\r")) +",";
                        }
                        diemdung = "Chuyến bay có điểm dừng tại" + diemdung;
                    }
                    chuyenBay.MaChuyenBay = aircraftcode.InnerText;
                    chuyenBay.HangHangKhongID = HangHangKhongDAO.SelectByName(Constants.JESSTAR_NAME).HangHangKhongID;
                    chuyenBay.DiemDiID = DiaDiemDAO.SelectByCode(diemDi).DiaDiemID;
                    chuyenBay.DiemDenID = DiaDiemDAO.SelectByCode(diemDen).DiaDiemID;
                    chuyenBay.DiemDung = diemdung;
                    chuyenBay.NgayDi = ngaydi;
                   

                    int chuyenBayID = ChuyenBayDAO.Insert(chuyenBay);

                    if (chuyenBayID > 0)
                    {
                        ChiTietChuyenBay chiTietChuyenBay = new ChiTietChuyenBay();
                        chiTietChuyenBay.ThoiGianDi = DepartTime.InnerText;
                        chiTietChuyenBay.ThoiGianDen = ArriveTime.InnerText;
                        chiTietChuyenBay.ChuyenBayID = chuyenBayID;
                        chiTietChuyenBay.DiemDiID = chuyenBay.DiemDiID;
                        chiTietChuyenBay.DiemDenID = chuyenBay.DiemDenID;

                        ChiTietChuyenBayDAO.Insert(chiTietChuyenBay);

                        GiaVe giaVe = new GiaVe();
                        giaVe.LoaiGiaVeID = 10;
                        giaVe.ChuyenBayID = chuyenBayID;
                        giaVe.Gia = Price;
                        giaVe.ChoNgoi = "";

                        GiaVeDAO.Insert(giaVe);
                    }
                    
                }
                
                catch (Exception ex) { continue; }
            }
            numFlights = 0;
        }

        public HtmlDocument MakeUrl(string diemDi, string diemDen, int ngaydi, int thangdi)
        {
            data = "__EVENTTARGET=" +
            "&__EVENTARGUMENT=" +
            "&__VIEWSTATE=/wEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFJ01lbWJlckxvZ2luU2VhcmNoVmlldyRtZW1iZXJfUmVtZW1iZXJtZTxtWS/I2BXFBfalk96y3LBuGXXD" +
            "&pageToken=" +
            "&total_price=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$RadioButtonMarketStructure=" + typeFlight[0] +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin1=" +diemDi+
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination1="+diemDen+
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate1=" + ngaydi.ToString() + "/" + thangdi.ToString() + "/" + DateTime.Now.Year.ToString() +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate1=18/01/2013" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListCurrency=VND" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin2=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination2=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate2=18/01/2013" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate2=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin3=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination3=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate3=25/12/2012" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate3=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin4=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination4=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate4=01/01/2013" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate4=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin5=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination5=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate5=08/01/2013" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate5=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketOrigin6=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextBoxMarketDestination6=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDepartureDate6=15/01/2013" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$TextboxDestinationDate6=" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_ADT=1" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_CHD=0" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_INFANT=0" +
            "&ControlGroupSearchView$AvailabilitySearchInputSearchView$ButtonSubmit=";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);

            request.ProtocolVersion = HttpVersion.Version10;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.KeepAlive = true;
            CookieContainer cookieJar = new CookieContainer();
            request.CookieContainer = cookieJar;

            byte[] postBytes = Encoding.UTF8.GetBytes(data);

            request.ContentLength = postBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.WriteTimeout = 10000;
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string abc = new StreamReader(response.GetResponseStream()).ReadToEnd();
            document = new HtmlDocument();
            document.LoadHtml(abc);

            HtmlNodeCollection Flights = document.DocumentNode.SelectNodes("//div[@id='main']/div[4]/div[2]/div[1]/table/tbody/tr");

            if (Flights != null)
                numFlights = Flights.Count - 2;
            return document;
        }

      
        public string Replacestring(string a, string pat)
        {
            string pattern = pat;
            Regex myregex = new Regex(pattern);
            string ketqua = myregex.Replace(a, "");

            return ketqua;
        }

        public string GetPlaces(string a)
        {
            string pattern = "-";
            Regex myregex = new Regex(pattern);
            string[] ketqua = myregex.Split(a);

            return ketqua[1];
        }
    }
}
